﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace XrmLibrary.MsCrm4Adapter.Extensions
{
    public static class ConditionExpressionExtensions
    {
        public static Microsoft.Crm.Sdk.Query.ConditionExpression ToCrm4ConditionExpression(this Microsoft.Xrm.Sdk.Query.ConditionExpression crm2011ConditionExpression)
        {
            Microsoft.Crm.Sdk.Query.ConditionExpression crm4ConditionExpression =
                new Microsoft.Crm.Sdk.Query.ConditionExpression()
                {
                    AttributeName = crm2011ConditionExpression.AttributeName,
                    Operator = crm2011ConditionExpression.Operator.ToCrm4ConditionOperator(),
                    Values = crm2011ConditionExpression.Values.ToArray()
                };

            return crm4ConditionExpression;
        }

        public static IEnumerable<object> ToCrm4ValueCollection(this Microsoft.Xrm.Sdk.DataCollection<object> crm2011DataCollection)
        {
            foreach (object o in crm2011DataCollection)
            {
                yield return o;
            }
        }

        public static IEnumerable<Microsoft.Crm.Sdk.Query.ConditionExpression> ToCrm4ConditionExpressionCollection(this Microsoft.Xrm.Sdk.DataCollection<Microsoft.Xrm.Sdk.Query.ConditionExpression> crm2011DataCollection)
        {
            foreach (Microsoft.Xrm.Sdk.Query.ConditionExpression conditionExpression in crm2011DataCollection)
            {
                yield return conditionExpression.ToCrm4ConditionExpression();
            }
        }

        public static Microsoft.Xrm.Sdk.Query.ConditionExpression ToCrm2011ConditionExpression(this Microsoft.Crm.Sdk.Query.ConditionExpression crm4ConditionExpression)
        {
            Microsoft.Xrm.Sdk.Query.ConditionExpression crm2011ConditionExpression =
                new Microsoft.Xrm.Sdk.Query.ConditionExpression()
                {
                    AttributeName = crm4ConditionExpression.AttributeName,
                    Operator = crm4ConditionExpression.Operator.ToCrm2011ConditionOperator(),
                };

            // Set Values.
            crm2011ConditionExpression.Values.AddRange(crm4ConditionExpression.Values);

            return crm2011ConditionExpression;
        }

        public static IEnumerable<Microsoft.Xrm.Sdk.Query.ConditionExpression> ToCrm2011ConditionExpressionCollection(this ArrayList crm4ConditionExpression)
        {
            foreach (Microsoft.Crm.Sdk.Query.ConditionExpression conditionExpression in crm4ConditionExpression)
            {
                yield return conditionExpression.ToCrm2011ConditionExpression();
            }
        }
    }
}
